define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'jstree'], function ($, undefined, Backend, Table, Form) {
    var Controller = {
        index: function () {
            var platform = $('#tabs-platform>li.active>a').data('value');
            var tabletype = $('#tabs-tabletype>li.active>a').data('value');
            var isSyncDepList = false;
            $(document).on('click', '#btn-refresh-department', function () {
                isSyncDepList = true; // 重新同步部门列表
                $('#tree-department').jstree().refresh();
            });
            $(document).on('click', '#expandall', function () {
                $(this).data('expandall',!$(this).data('expandall'));
                $(this).html($(this).data('expandall') ? '<i class="fa fa-minus"></i> 全部折叠' : '<i class="fa fa-plus"></i> 全部展开');
                $('#tree-department').jstree($(this).data('expandall') ? 'open_all' : 'close_all');
            });
            $('#toolbar-user .btn-refresh').on('click', function () {
                table.bootstrapTable('refresh');
            });
            
            var remoteTableColums = [
                [
                    {field: 'avatar', title:'头像', formatter: Table.api.formatter.image},
                    {field: 'userid', title:'平台UserId'},
                    {field: 'name', title: '姓名'},
                    {field: 'position', title: '职位'},
                    {field: 'mobile', title: '手机号'},
                    {field: 'email', title: '邮箱'},
                    {field: 'active', title: '钉钉激活状态', formatter: function(value,row){ return value ? '<i class="fa fa-bell text-success"></i> 已激活' : '<i class="fa fa-bell-slash text-gray"></i> 未激活'}},
                    {field: 'isbind', title: '本地账号绑定', formatter: function(value,row){ return value ? '<i class="fa fa-check text-success"></i> 已绑定' : '<i class="fa fa-close text-danger"></i> 未绑定'}}
                ]
            ];
            var localTableColums = [
                [
                    {field: 'id', title: 'ID', sortable: true},
                    {field: 'user_id', title: '本地用户ID', sortable: true},
                    {field: 'platform', title: '第三方平台', formatter:function(value){
                        if (value === 'dingtalk') return '钉钉';
                        if (value === 'wechatwork') return '企业微信';
                        if (value === 'feishu') return '飞书';
                    }},
                    {field: 'openuserid', title: '第三方平台userid', sortable: true},
                    {field: 'openname', title: '第三方平台昵称', sortable: true},
                    {field: 'createtime', title: '创建时间', operate: 'RANGE', addclass: 'datetimerange', sortable: true, formatter: Table.api.formatter.datetime},
                    {field: 'updatetime', title: '更新时间', operate: 'RANGE', addclass: 'datetimerange', sortable: true, formatter: Table.api.formatter.datetime},
                    {field: 'logintime', title: '登录时间', operate: 'RANGE', addclass: 'datetimerange', sortable: true, formatter: Table.api.formatter.datetime},
                    {field: 'id', title: __('Operate'), formatter: Controller.api.formatter.unbind}
                ]
            ];
            var tableOptions = {
                commonSearch: false,
                search: false,
                pageSize: 10,
                pageList: [10, 20, 50, 'All'],
                url: 'thirdwork/getDepartmentUserList',
                queryParams: function (params) {
                    params.department_id = $('#tree-department').jstree().get_selected()[0];
                    params.platform = platform;
                    params.tabletype = tabletype;
                    return params;
                },
                columns: remoteTableColums
            };
            
            $('#tree-department').jstree({
                'plugins': ['types', 'state'],
                'themes': {
                    'stripes': true
                },
                'core': {
                    'multiple': false,
                    'check_callback': false,
                    'strings': {
                        'Loading ...' : '获取中...'
                    },
                    'data': function (node, callback) {
                        Fast.api.ajax({
                            url: 'thirdwork/getDepartmentList',
                            data: {platform: platform, isSyncDepList: isSyncDepList}
                        }, function (data,ret) {
                            isSyncDepList = false;
                            callback.call(this,ret['data']);
                            return false;
                        },function (data,ret) {
                            callback.call(this,[]);
                        });
                    },
                }
            }).on('select_node.jstree',function(e,data){
            	tableOptions.pagination = platform === 'wechatwork' && tabletype === 'remotelist' ? false : true;
                table.bootstrapTable('refreshOptions', tableOptions);
            });

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    del_url: 'thirdwork/del',
                },
                commonSearch: false,
                search: false,
            });
            var table = $('#table');
            
            // 为表格绑定事件
            Table.api.bindevent(table);
            
            //在表格内容渲染完成后回调的事件
            table.on('post-body.bs.table', function (e, json) {
                // 单个解绑按钮
                $('.btn-del').on('click', function () {
                    var id = $(this).data('id');
                    Layer.confirm('确定解绑（即删除）此用户吗？', {
                        icon: 3,
                        title: '操作确认',
                    }, function (index) {
                        Fast.api.ajax({
                            url: 'thirdwork/del',
                            data: {ids: id}
                        }, function (data,ret) {
                            table.bootstrapTable('refresh', {});
                        });
                        Layer.close(index);
                    });
                });
            });

            // 初始化表格
            table.bootstrapTable();
            
            // 移除默认的TAB事件
            $('.panel-heading [data-field] a[data-toggle="tab"]').unbind('shown.bs.tab');

            // 分别绑定新的TAB事件
            $('#tabs-platform>li>a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                platform = $(this).data('value');
                $('#tree-department').jstree().refresh();
            });
            $('#tabs-tabletype>li>a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                tabletype = $(this).data('value');
                if (tabletype === 'isbind' || tabletype === 'all') {
                    tableOptions.columns = localTableColums;
                    tableOptions.url = 'thirdwork/getLocalDepartmentBindList';
                }else{
                    tableOptions.columns = remoteTableColums;
                    tableOptions.url = 'thirdwork/getDepartmentUserList';
                }
                if (tabletype === 'all') {
                    $('#bar-department').hide(100);
                    $('#panel-user').removeClass('col-md-9').addClass('col-md-12');
                }else{
                    $('#bar-department').show(100);
                    $('#panel-user').removeClass('col-md-12').addClass('col-md-9');
                }
                tableOptions.pageNumber = 1;
                $('#tree-department').jstree().refresh();
            });
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($('form[role=form]'));
            },
            formatter: {
                unbind: function(value, row, index) {
                    return '<a href="javascript:;" class="btn btn-danger btn-xs btn-del" data-id="'+value+'"><i class="fa fa-trash-o"></i> 解绑</a>';
                }
            }
        }
    };
    return Controller;
});